#!/bin/sh

# ---------------------------------------------------------------------------
# Solaris' /bin/sh uses a braindead builtin echo, circumvent
# ---------------------------------------------------------------------------
TEST=`echo -n ""`
if [ -z "$TEST" ]; then
  ECHON="echo -n"
  NNL=""
else
  ECHON="echo"
  NNL="\c"
fi

genversion() {
    hg parents -b >/dev/null 2>&1 || BRANCH=$(hg tags | { read a; read line; tipmost=`echo "$line" | cut -f1 -d" "`; echo "$tipmost"; })
    if [ -z "$BRANCH" ]; then BRANCH=`hg parents -b --template '{branches}\n'`; fi
	if [ -z "$DISTRO" ]; then
	  DISTRO="generic"
	fi
	
	ACTUALTAG=`hg id | cut -f2 -d" "`
	if [ "$ACTUALTAG" = "$BRANCH" ]; then
	  $ECHON "${BRANCH}-${DISTRO}$NNL"
	else
	  ACTUALID=`hg id | cut -f1 -d" " | sed -e "s/+$//"`
	  $ECHON "${BRANCH}-${DISTRO}-${ACTUALID}"
	fi
	DIFC=`hg diff | wc -l | sed -e "s/ //g"`
	if [ "$DIFC" = "0" ]
	then
	    echo ""
	else
	    echo "-plus"
	fi
}

if [ -f version.id ]; then
   BUILD_VERSION=`head -1 < version.id`
  if [ -z "${BUILD_VERSION}" ]; then
    echo "% Format error in version.id file"
    exit 1
  fi
else 
  hg id >/dev/null 2>&1 || {
    echo "% No mercurial repository and no version.id file found" >&2
    exit 1
  }
fi

FILENAME="$1"

BUILD_USER=`whoami`
BUILD_HOST=`hostname`
BUILD_DATE=`date +%Y-%m-%dT%H:%M:%S`
if [ -z "$BUILD_VERSION" ]; then
  BUILD_VERSION=`genversion`
  echo "$BUILD_VERSION" > version.id
fi
BUILD_SHORTVERSION=`echo "$BUILD_VERSION" | cut -f1 -d-`

if [ -z "$1" ]; then
  echo "% Variables detected:"
  echo "%BUILD_USER%: $BUILD_USER"
  echo "%BUILD_HOST%: $BUILD_HOST"
  echo "%BUILD_DATE%: $BUILD_DATE"
  echo "%BUILD_VERSION: $BUILD_VERSION"
  echo "%BUILD_SHORTVERSION: $BUILD_SHORTVERSION"
  echo
  echo "% Usage: mkversion <filename>"
  echo "         Will build <filename> from <filename>.in"
  exit 1
fi

if [ ! -f "${FILENAME}.in" ]; then
  echo "File ${FILENAME}.in not found"
  exit 1
fi

cat "${FILENAME}.in" | sed -e "s/%BUILD_SHORTVERSION%/${BUILD_SHORTVERSION}/;s/%BUILD_VERSION%/${BUILD_VERSION}/;s/%BUILD_HOST%/${BUILD_HOST}/;s/%BUILD_USER%/${BUILD_USER}/;s/%BUILD_DATE%/${BUILD_DATE}/" \
	> ${FILENAME}

